import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import _config from "../utils/config";
import { jsonToTreeJson } from "../utils";
import reqTools from "../utils/reqTools";
const normalAxios = axios.create();
const mockAxios = axios.create();

// mock 数据
var mock = new MockAdapter(mockAxios);

mock.onPost('/login').reply(config => {
  let postData = JSON.parse(config.data);

  return new Promise(function (_resolve, reject) {
    normalAxios.post(
      _config.primary + '/api/sysUser/login',
      {
        loginId: postData.user,
        password: postData.password
      },
      {
        headers: { 'Content-Type': 'application/json' }
      }
    ).then((_res) => {
      if (_res.data.code != 0) {
        _resolve([500, { message: "请输入正确的用户名或密码" }]);
      } else {
        normalAxios.post(
          _config.primary + '/api/token',
          {
            loginId: postData.user,
            password: postData.password
          },
          {
            headers: { 'Content-Type': 'application/json' }
          }
        ).then((res) => {
          let data = _res.data.data;
          data.token = res.data.data.token;
          data.password = postData.password;
          _resolve([200, data]);
        }).catch((err) => {
          _resolve([500, { message: "请输入正确的用户名或密码" }]);
        });
      }
    }).catch((err) => {
      _resolve([500, { message: "请输入正确的用户名或密码" }]);
    });
  });
});

mock.onGet('/logout').reply(200, {});
mock.onGet('/my').reply(200, require('./mock/user'));
mock.onGet('/menu').reply((config) => {
  return new Promise(function (resolve, reject) {
    reqTools.get('/api/sysMenu/user', config.params).then(res => {
      resolve([200, res.data]);
    }).catch((err) => {
      resolve([500, err]);
    });
  });
});

export default mockAxios;
